<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/1/23
 * Time: 9:57
 */
namespace app\admin\controller;
use think\Controller;
use think\Request;
use think\Db;
class Base extends Controller 
{
	
    public function __construct(){
		//初始化父类的方法
        parent::__construct();
		if (!session_id()) session_start();
		if(empty($_SESSION['username'])){
			$this->error('你没有登录','index.php/admin/login/login');	
            			
		}
        if(empty($_SESSION['power'])){
           $this->getRolePower();    
       } 
        
		$nowrequest=request()->controller().'/'.request()->action(); 
        $quanxian=json_decode($_SESSION['power']);
        if($_SESSION['role_name']!='admin'){
        	if(!in_array($nowrequest,$quanxian)){
         	  $this->error('你没有权限','admin/Index/index'); 
        	}
        }


    }

     public function getRolePower(){

     	$userid=$_SESSION['userid'];

        $userinfo= Db::query("select * from user where user_id='$userid' ");         //获取登录这的user_id
        $user_id=$userid;
        $userrole=Db::query("select * from user_role where user_id =$user_id ");    //获取登录这的role_id
        $role_id=$userrole[0]['role_id'];
        $roleinfo=Db::query("select * from role where role_id =$role_id ");         //获取role的角色信息
        $_SESSION['role_name']=$roleinfo[0]['role_name'];
        $power=Db::query("select * from role_power where role_id = $role_id ");      //获取该角色所有的权限id

        $arr=array();

        foreach ($power as $key => $value) {
            foreach ($value as $k => $v) {
                if($k=='power_id'){
                    $arr[]=$v;
                }
            }
        }
        $powerid=implode(',',$arr);
        $data=array();

        $powername=Db::query("select * from power where power_id in ($powerid) "); 
        foreach ($powername as $key => $value) {
            foreach ($value as $k => $v) {
                if($k=='power_controllername'){
                    $data[$key]['c']=$v;
                }
                if($k=='power_actionname'){
                    $data[$key]['a']=$v;
                }
            }
        }

        foreach ($data as $key => $value) {
            $quanxian[]=implode('/',$value);
        }
        $_SESSION['power']= json_encode($quanxian);
        
    }
}